<template>
  <div class="pulldown">
    <div class="chat-msg-list" ref="wrapper">
      <div class="content">
        <div class="pulldown-wrapper">
          <div v-show="beforePullDown">
            <span>下拉加载更多聊天记录</span>
          </div>
          <div v-show="!beforePullDown">
            <div v-show="isPullingDown">
              <van-loading size="24px" >加载中...</van-loading>
            </div>
            <div v-show="!isPullingDown">
              <span>加载成功</span>
            </div>
          </div>
        </div>
        <div class="list">
          <template v-for="item in chatHistoryList">
            <ChatMsgText
              v-if="item.type === 'text'"
              :key="item.uuid"
              :content="item.content"
              :avatar="item.avatar"
              :align="getChatItemAlign(item)"
            />
            <ChatMsgAudio
              v-else-if="item.type === 'audio'"
              :key="item.uuid"
              :url="item.url"
              :avatar="item.avatar"
              :align="getChatItemAlign(item)"
              :duration="item.duration"
            />
            <ChatMsgImage
              v-else-if="item.type === 'image'"
              :key="item.uuid"
              :url="item.url"
              :avatar="item.avatar"
              :align="getChatItemAlign(item)"
              @load="handleImageLoad"
            />
            <ChatMsgFile
              v-else-if="item.type === 'file'"
              :key="item.uuid"
              :url="item.url"
              :fileName="item.fileName"
              :avatar="item.avatar"
              :align="getChatItemAlign(item)"
              :size="item.size"
              :loaded="item.loaded"
            />
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import BScroll from '@better-scroll/core'
import PullDown from '@better-scroll/pull-down'
import ScrollBar from '@better-scroll/scroll-bar'
import MouseWheel from '@better-scroll/mouse-wheel'
import ChatMsgAudio from '@/components/ChatMsgAudio'
import ChatMsgImage from '@/components/ChatMsgImage'
import ChatMsgText from '@/components/ChatMsgText'
import ChatMsgFile from '@/components/ChatMsgFile'
const TIME_BOUNCE = 800
export default {
  name: 'ChatMsgList',
  components: {
    ChatMsgAudio,
    ChatMsgImage,
    ChatMsgText,
    ChatMsgFile
  },
  props: {
    contactId: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      scroll: null,
      beforePullDown: true,
      isPullingDown: false
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'chatHistory']),
    chatHistoryList() {
      const res = this.chatHistory[this.contactId]
      return res
    }
  },
  async mounted() {
    await this.initChatHistory(this.contactId)
    this.$nextTick(() => {
      if (!this.scroll) {
        this.initScroll()
      }
    })
  },
  methods: {
    ...mapActions({
      initChatHistory: 'chatList/initChatHistory',
      setChatUnread: 'chatList/setChatUnread',
      getChatHistory: 'chatHistory/getChatHistory'
    }),
    getChatItemAlign(item) {
      return item.from === this.userInfo.id ? 'right' : 'left'
    },
    initScroll() {
      BScroll.use(PullDown).use(ScrollBar).use(MouseWheel)
      const scroll = new BScroll(this.$refs.wrapper, {
        scrollY: true,
        scrollbar: true,
        bounceTime: TIME_BOUNCE,
        pullDownRefresh: true,
        mouseWheel: true,
        click: true
      })
      this.scroll = scroll
      this.scrollBottom()
      const hooks = scroll.scroller.actionsHandler.hooks
      hooks.on('click', () => { document.activeElement.blur() })
      scroll.on('pullingDown', this.pullingDownHandler)
      window.myscroll = this.scroll
    },
    async pullingDownHandler() {
      console.log('下拉获取更多----')
      this.beforePullDown = false
      this.isPullingDown = true
      const { maxScrollY: prevMaxY } = this.scroll
      let count = 0
      try {
        count = await this.getChatHistory(this.contactId)
      } catch (e) {
        console.log(e)
      } finally {
        this.isPullingDown = false
        this.beforePullDown = true
        const offset = 60
        this.scroll.finishPullDown()
        if (count === 0) {
          this.$toast.fail('没有更多聊天记录了')
        } else {
          this.scroll.refresh()
          const { maxScrollY: nowMaxY } = this.scroll
          const dest = nowMaxY - prevMaxY + offset
          this.scroll.scrollTo(0, dest, 0)
        }
      }
    },
    scrollBottom(time = 0) {
      console.log('滚动到最尾---')
      const { maxScrollY } = this.scroll
      this.scroll.scrollTo(0, maxScrollY, time)
    },
    refresh() {
      if (this.scroll) {
        this.scroll.refresh()
      }
    },
    handleImageLoad() {
      this.refresh()
      // this.scrollBottom()
    }
  },
  sockets: {
    text(res) {
      const { from } = res
      if (from === this.contactId) {
        this.setChatUnread({ contactId: this.contactId, unread: 0 })
        setTimeout(() => {
          this.refresh()
          this.scrollBottom(500)
        }, 0)
      }
    },
    audio(res) {
      const { from } = res
      if (from === this.contactId) {
        this.setChatUnread({ contactId: this.contactId, unread: 0 })
        setTimeout(() => {
          this.refresh()
          this.scrollBottom(500)
        }, 0)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-msg-list {
  height: calc(calc(var(--vh) * 100) - #{$chat-input-height + $nav-bar-height});
  box-sizing: border-box;
  .content {
    padding: $padding-side;
    background-color: #eeeeee;
    position: relative;
  }
  .pulldown-wrapper{
    position :absolute;
    width :100%;
    padding: 20px;
    box-sizing: border-box;
    transform :translateY(-100%) translateZ(0);
    text-align :center;
    color :#999;
  }
}
</style>
